﻿using ChessTest.Chess.Items;
using org.xisoft.game.utils.game;
using System.Collections.Generic;

namespace ChessTest.Chess.Algorithms
{
    /// <summary>
    /// 负极值算法
    /// </summary>
    class NegaMaxAlgorithm : AiAlgorithm
    {

        public override MoveAction Search(AiChessboard aiChessboard, int depth)
        {
            return NegaMax(aiChessboard, depth);
        }


        private MoveAction NegaMax(AiChessboard aiChessboard,int depth)
        {
            if (depth <= 0)
            {
                return new MoveAction();
            }




            MoveAction bestChildstep = null;

            List<MoveAction> canMoveActionList = GetAllCanMoves(aiChessboard);
            foreach (MoveAction action in canMoveActionList)
            {

                aiChessboard.Move(action.CurrentChessman as Chessman, action.ToX, action.ToY);

                MoveAction step = NegaMax(aiChessboard,depth - 1);


                action.Score -= step.Score;


                aiChessboard.Undo();
                if (bestChildstep == null || bestChildstep.Score < action.Score)
                    bestChildstep = action;


            }


            if (bestChildstep == null)
            {
                bestChildstep = new MoveAction { Score = -1000 - depth * 10 };
            }


            return bestChildstep;
        }
    }
}
